/**
 * FtpContentServiceImpl.java
 */
package org.yate.oa.service.imp;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yate.oa.dao.IBaseMapperDao;
import org.yate.oa.dao.mapper.FtpContentMapper;
import org.yate.oa.exception.FtpOperateException;
import org.yate.oa.model.FtpContent;
import org.yate.oa.service.FtpContentService;

/**
 * @author Yate
 * @date Jul 19, 2014
 * @description TODO
 * @version 1.0
 */
@Service
public class FtpContentServiceImpl extends BaseService<FtpContent, Long>
		implements FtpContentService {
	
	private final static Logger log = LoggerFactory.getLogger(FtpContentService.class);

	@Value("${nfs.root.dir}")
	private String ftpRootDir;
	
	@Resource
	private FtpContentMapper mapper;

	public FtpContent store(byte[] d, FtpContent e) throws FtpOperateException {
		try {
			File f = new File(ftpRootDir + e.getKey() + File.separator
					+ e.getValue());
			if (!f.exists()) {
				FileUtils.forceMkdir(new File(ftpRootDir + e.getKey()));
				FileUtils.touch(f);
				FileUtils.writeByteArrayToFile(f, d);
			}
			this.add(e);
		} catch (IOException ex) {
			log.error(ex.getMessage(), ex);
			throw new FtpOperateException("文件上传失败");
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw new FtpOperateException("文件上传失败");
		}
		return e;
	}

	protected IBaseMapperDao<FtpContent, Long> getMapperDao() {
		return mapper;
	}
}
